package org.thesis.activity;

import java.util.ArrayList;
import java.util.List;

import org.thesis.doituong.attach;
import org.thesis.doituong.sender;
import org.thesis.doituong.showToast;
import org.thesis.mailControl.GmailControl;
import org.thesis.mailControl.HotmailControl;
import org.thesis.mailControl.MdeamonControl;
import org.thesis.mailControl.YahooControl;
import org.thesis.xuly.XuLyChuoi;

import org.thesis.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

public class newmailActivity extends Activity
{
	final static String SIGN = "SignByEsafe@";
	final static String KEY_SIGN = "KEY_SIGN";
	final static String KEY_ARRAY_TO_NEWMAIL = "KeyArrToNewMail";
	final static String LOAI_SEND = "LOAISEND";
	final static String NEWMAIL = "NEWMAIL";
	final static String REPLY = "REPLY";
	final static String FORWARD = "FORWARD";
	final static String KEY_CHUOI_MESS_ENCRYPT = "CHUOI_MESS_ENCRYPT";
	final static String KEY_NGUOIGUI_NGUOINHAN = "KEY_NGUOIGUI_NGUOINHAN";
	final static String KEY_SUB_TEMP = "SUB TEMPLATES";
	final static  int RESULT_ENCRYPT = 1234;
	final static String KEY_NGUOIGUI = "NGUOIGUI";
	final static String KEY_NGUOINHAN = "NGUOINHAN";
	final static String KEY_CONTACT = "key_contact";
	final static int RESULT_GET_ECONTACT = 55;
	final static int REQUEST_CHUOI_ATTACH_SEND = 99;
	final static String KEY_CHUOI_ATTACH_SEND = "chuoi_attach_send";
	final static String KEY_MESSAGE = "MEASSAGE BODY";
	final static String KEY_USERNAME_LOGIN = "USERNAMELOGIN"; // nhan USERVA PASS tu showmail activity gui toi de login
	final static String KEY_PASSWORD_LOGIN = "PASSWORDLOGIN";
	final static String KEY_SUB = "SUB";
	final static String KEY_TO = "TO";
	final static String KEY_BODY = "BODY";
	showToast d;
	EditText  txt_sub, txt_body;
	TextView txt_from, txt_att, txt_int_att, 
			txt_bodyEnc;
//	ImageButton img_int_att;
	AutoCompleteTextView txt_to;
	String username , password, loai_email, tag = "newmailActivity", str_email = "",str_att;
	//
	
	ListView list;
	ArrayAdapter<String>adapter;
	XuLyChuoi xlchuoi ;
	
	GmailControl g;
	YahooControl y;
	HotmailControl h;
	MdeamonControl mdeamon;
	
	//
	
	List<String>list_to ; //ds ng nhan
	List<String>listatt; 
	int position;
	boolean flag_remove = false,
			flag_encrypt = false;//xac dinh xem thu co ma hoa hay khong
	int requestcode = 1, first_click = 0;
	String []value; //bien nhan gia tri ben readmail gui toi
	String sub_re, 
			loai_send,
			body_plantext, //nd luc chua ma hoa
			body_encrypt; //nd mail khi ma hoa
		
	
	
	protected void onCreate(Bundle savedInstanceState) 
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		d = new showToast(getBaseContext());
		setContentView(R.layout.newmail);
		value = new String[10];
		value = getIntent().getStringArrayExtra(KEY_ARRAY_TO_NEWMAIL);
		username = value[0];
		password = value[1];
		loai_send = value[2];
		sub_re = value [3];
		Log.v(tag, "nhan dc : " +username );
		//
		g = new GmailControl(username, password);
		y = new YahooControl(username, password);
		h = new HotmailControl(username, password);
		mdeamon = new MdeamonControl(username, password);
		//
		xlchuoi = new XuLyChuoi();
		loai_email = xlchuoi.kt_loai_email_login(username);
		
		//
		txt_sub = (EditText)findViewById(R.id.txt_newmail_sub);
		txt_body = (EditText)findViewById(R.id.txt_newmail_body);
		txt_to = (AutoCompleteTextView)findViewById(R.id.txt_newmail_to);
		txt_from = (TextView)findViewById(R.id.txt_newmail_from);
		txt_bodyEnc = (TextView) findViewById(R.id.txt_newmail_bodyEnc);
		body_encrypt = getResources().getString(R.string.Not_encrypt_sign);
		txt_bodyEnc.setText(body_encrypt);
		txt_from.setText("From : " + username);
		txt_int_att = (TextView) findViewById(R.id.txt_newmail_int_att);
		txt_int_att.setText("0");
		//
		list_to = new ArrayList<String>();
		listatt = new ArrayList<String>();
		str_att = "";
		
		if(loai_send.equals(REPLY))
		{
			txt_sub.setText(sub_re);
			txt_to.setText(value[4]);
		}else if(loai_send.equals(FORWARD))
		{
			Log.v(tag +"tttttttttttttt" , "str_att ==== " +str_att);
			str_att = value[5];
			listatt = new ArrayList<String>();
			if(str_att.length() == 0)
			{
				Log.v(tag, "chang nhan dc ji");
			}
			else
			{
				String []str_arr_att = str_att.split(";");
				for(String str_1_att : str_arr_att)
				{
					listatt.add(str_1_att);
					Log.v(tag, "add vao attach : " + str_1_att);
				}
				
			}
			txt_int_att.setText(String.valueOf(listatt.size()));
			txt_sub.setText(sub_re);
			txt_body.setText(value[4]);
			Log.v(tag +"mmmmmmmmmmmmm" , "str_att ==== " +str_att);
		}
		
		
	}
	
	public void img_onClick(View v)
	{
		ImageButton btn = (ImageButton)v;
		switch (btn.getId()) {
		case R.id.img_newmail_backA:
			finish();break;
		case R.id.img_newmail_int_att:
			Intent intent = new Intent(this, attach_send_manager.class);
			intent.putExtra(KEY_CHUOI_ATTACH_SEND, str_att);
			startActivityForResult(intent,requestcode);
			Log.v(tag, "doi result tu attach_send_manager ...");
			break;
		case R.id.img_newmail_addRecipients:
//			startActivity(new Intent(this, uit.mmt02.activity.get_econtact_Activity.class));
			Log.v(tag, "add econtactnclick");
			if(first_click == 0 )
			{
				str_email += txt_to.getText().toString().trim();
				
			}
			first_click ++;
			startActivityForResult((new Intent(this, org.thesis.activity.get_econtact_Activity.class)),requestcode);
			break;
		case R.id.img_newmail_send:
			send();
			break;
		/*case R.id.img_newmail_encrypt:
			newmail_encrypt();
			break;*/
		case R.id.img_newmail_esafe:
			openOptionsMenu();
			break;

		default:
			break;
		}
	}
	public void btn_onClick(View v)
	{
		Button btn = (Button)v;
		switch (btn.getId()) {
//		case R.id.btn_add_attach:
//			startActivityForResult(new Intent(this, attach_send_manager.class),requestcode);
//			Log.v(tag, "doi result tu attach_send_manager ...");
//			break;
		case R.id.btn_newmail_subtemp:
			Intent intent = new Intent(this,sub_templatesActivity.class);
			startActivityForResult(intent, requestcode);
		default:
			break;
		}
	}
	

	//khoi tao menu send
	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{
		// TODO Auto-generated method stub
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_newmail, menu);
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) 
	{
		// TODO Auto-generated method stub
		switch (item.getItemId()) 
		{
		case R.id.item_send:
			send();
			break;
		case R.id.item_add:
			if(first_click == 0 )
			{
				str_email += txt_to.getText().toString().trim();
				
			}
			first_click ++;
			startActivityForResult((new Intent(this, org.thesis.activity.get_econtact_Activity.class)),requestcode);
			break;
		case R.id.item_attach:
			Intent intent = new Intent(this, attach_send_manager.class);
			intent.putExtra(KEY_CHUOI_ATTACH_SEND, str_att);
			startActivityForResult(intent,requestcode);
			Log.v(tag, "doi result tu attach_send_manager ...");
			break;
		case R.id.item_save:
			d.showmess("savve");
			break;
		case R.id.item_discard:
			d.showmess("Discard");
		/*case R.id.item_mahoa:
			newmail_encrypt();*/
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (resultCode) {
		case RESULT_OK: //nhan chuoi sub temp
			String s = data.getStringExtra(KEY_SUB_TEMP);
			txt_sub.setText(s);
			break;
		case RESULT_ENCRYPT: // ket qua ma hoa gui ve
			str_att = data.getStringExtra(KEY_CHUOI_ATTACH_SEND); // nhan chuoi att ma hoa
			String str_mess_encrypt = data.getStringExtra(KEY_CHUOI_MESS_ENCRYPT);
			String str_sign = data.getStringExtra(KEY_SIGN);
			Log.v(tag, "chuoi sau khi ma hoa : " + str_mess_encrypt);
			Log.v(tag, "nhan duoc chuoi attach ma hoa " + str_att);
//			String text = str_mess_encrypt + "\n\r" 
//					+ "******************** \n\r" + "sign@" + str_sign;
//			txt_body.setText(text);
			flag_encrypt = true;
			body_encrypt = str_mess_encrypt; // neu co ma hoa tra ve chuoi ma hoa, ko ma hoa tra ve chuoi plantext
			if(str_sign.length() > 0) // neu co ky
			{
				body_encrypt +=  "\n\r" 
						+ "************************** \n\r" + SIGN + str_sign + "@sign";
			}
			
			txt_bodyEnc.setText(body_encrypt);
			//gan vao listatt de gui di
			listatt = new ArrayList<String>();
			if(str_att.length() == 0)
			{
				Log.v(tag, "chang nhan dc ji");
			}
			else
			{
				String []str_arr_att = str_att.split(";");
				for(String str_1_att : str_arr_att)
				{
					listatt.add(str_1_att);
					Log.v(tag, "add vao attach : " + str_1_att);
				}
				
			}
			
			for(String str_1_att2 : listatt)
			{
				Log.v(tag, "att da add : " + str_1_att2);
			}
			
			txt_int_att.setText(String.valueOf(listatt.size()));
			break;
		case REQUEST_CHUOI_ATTACH_SEND:
			str_att = data.getStringExtra(KEY_CHUOI_ATTACH_SEND);
			Log.v(tag, "nhan dc reselt " + REQUEST_CHUOI_ATTACH_SEND + "chuoi " + str_att);
			listatt = new ArrayList<String>();
			if(str_att.length() == 0)
			{
				Log.v(tag, "chang nhan dc ji");
			}
			else
			{
				String []str_arr_att = str_att.split(";");
				for(String str_1_att : str_arr_att)
				{
					listatt.add(str_1_att);
					Log.v(tag, "add vao attach : " + str_1_att);
				}
				
			}
			
			for(String str_1_att2 : listatt)
			{
				Log.v(tag, "att da add : " + str_1_att2);
			}
			
			txt_int_att.setText(String.valueOf(listatt.size()));
//			Log.v(tag, str_att);
//			Log.v(tag, "nhan dc result " + REQUEST_CHUOI_ATTACH_SEND);
			break;
		case RESULT_GET_ECONTACT:
			Log.v(tag, "nhan dc reselt " + RESULT_GET_ECONTACT);
			int t = (str_email.split("@")).length;
			Log.v(tag, "chieu dai : " + t);
			if((str_email.split("@")).length == 2 && first_click < 2)
				str_email += ";";
			str_email += data.getStringExtra(KEY_CONTACT);
			Log.v(tag, str_email);
			txt_to.setText(str_email);
//			String []str_arr_email = str_email.split(";");
//			for(String str_1_email : str_arr_email)
//			{
//				list_to.add(str_1_email);
//			}
//			Log.v(tag, "list_to size : " + list_to.size());
//			for(String tt :list_to)
//			{
//				Log.v(tag, tt);
//			}
			break;
		default:
			break;
		}
	}
	
	public void sendmail()
	{
		try 
		{
			Log.v(tag, "vao ham send mail");
			sender sd ;
			if(flag_encrypt)
			{
				sd = new sender(txt_sub.getText().toString(),body_encrypt, list_to,listatt);
			}else
				sd = new sender(txt_sub.getText().toString(),txt_body.getText().toString(), list_to,listatt);
			
			if(loai_email.startsWith("gmail"))
			{
				g.send(sd);
			}
			else if(loai_email.startsWith("yahoo"))
			{
				y.send(sd);
			}	//
			else if(loai_email.startsWith("hotmail"))
			{
				//
				h.send(sd);
			}
			else
			{
				mdeamon.send(sd);
			}
			
			d.showmess("send thanh cong");
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(tag, "err cho gui mail ???????????" + e.toString());
		}
		
	}
	
	private class send_async extends AsyncTask<String, Void, Void>
	{
		ProgressDialog p = new ProgressDialog(newmailActivity.this);
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			p.setMessage("sending....");
			p.show();
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(String... params) {
			// TODO Auto-generated method stub
			Log.v(tag, "do in send .. async..");
			sendmail();
			return null;
		}
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			
			p.dismiss();
			d.showmess(getResources().getString(R.string.send_success));
			super.onPostExecute(result);
		}
	}
	
	public void AlertDialogshow(String title, String mess, String button)
	{
		AlertDialog alert = new AlertDialog.Builder(this).create();
		alert.setTitle(title);
		alert.setMessage(mess);
		alert.setButton(button, new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				return;
				
			}
		});
		alert.show();
		
	}
	///
	/*public void newmail_encrypt(){///
		try{
			//Kiem tra nguoigui_nguoinhan hop le;
			boolean flag_hople;
//			if(txt_to.getText().toString().trim().equals("")||txt_sub.getText().toString().trim().equals("")||txt_body.getText().toString().trim().equals("")){
//				d.showmess("Ban phai nhap du thong tin: nguoi nhan, tieu de, noi dung mail");
			if (txt_to.getText().toString().trim().equals(""))
				d.showmess(getResources().getString(R.string.err_newmail_toblank));
			 else if (txt_body.getText().toString().trim().equals(""))
				d.showmess(getResources().getString(R.string.err_encrypt_plantext));
			else
			{
				String nguoigui_nguoinhan = username+";"+txt_to.getText().toString().trim();
//				d.showmess(nguoigui_nguoinhan);
				org.thesis.secutity.checkmailaddress checker = new org.thesis.secutity.checkmailaddress();
//				flag_hople = checker.kiemtrahoples(nguoigui_nguoinhan.split(";"));//true:hople;flase:ko hop le;
				flag_hople = checker.check_mailhople(nguoigui_nguoinhan);
				if(!flag_hople){
					d.showmess("nhap sai dia chi email nguoi nhan, nhap lai!!!");
				} else 
				{
					nguoigui_nguoinhan = nguoigui_nguoinhan.replaceAll(";", " ").trim();////
					Intent i_en = new Intent(this, encryptActivity.class);
					//
					i_en.putExtra(KEY_NGUOIGUI, username);
					i_en.putExtra(KEY_NGUOINHAN, txt_to.getText().toString());
					i_en.putExtra(KEY_MESSAGE, txt_body.getText().toString());
					i_en.putExtra(KEY_CHUOI_ATTACH_SEND, str_att);
					i_en.putExtra(KEY_NGUOIGUI_NGUOINHAN, nguoigui_nguoinhan);
					startActivityForResult(i_en, requestcode);
				}
			}
			
		}catch(Exception e){
			Log.v(tag, "ERROR: "+e);
		}
	}*/
	
	public void send()
	{
		try 
		{
			list_to = new ArrayList<String>();
			str_email = txt_to.getText().toString().trim();
			Log.v(tag, "chuoi to : " + str_email + "  " + str_email.length() );
			String []str_arr_email = str_email.split(";");
			for(String str_1_email : str_arr_email)
			{
				list_to.add(str_1_email);
			}
			Log.v(tag, "list_to size : " + list_to.size());
			for(String tt :list_to)
			{
				Log.v(tag, "gui toi : " + tt);
			}
			if(str_email.length() > 0 )
			{
				if(str_email.indexOf("@")>-1) // neu email dung dinh dang , co@
				{
					// thuc hien gui mail
					Log.v(tag, "goi async snd mail");
					new send_async().execute("");
				}else
				{
					AlertDialogshow(null,getResources().getString(R.string.email_err_dinhdang) , "OK");
				}
			}else
			{
				AlertDialogshow(null, getResources().getString(R.string.email_err_blank), "OK");
			}
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(tag, "send- loi send" +e.toString());
		}
	}
}
